<template>
  <PageWrapper v-loading="loading" loading-tip="加载中...">
    <div class="p-4 p-4-tag">
      <div class="tag">
        <div class="form-box">
          <BasicForm @register="registerForm" />
          <Tabs v-model:activeKey="activeKey">
            <Tabs.TabPane :forceRender="true" :key="1" tab="设备状态">
              <BasicForm @register="registerFormByStatus" />
            </Tabs.TabPane>
            <Tabs.TabPane :forceRender="true" :key="2" tab="设备变量">
              <BasicForm @register="registerFormByVariable" />
            </Tabs.TabPane>
          </Tabs>
          <div class="btns">
            <a-button class="btns-one" @click="handleResetFields" v-if="hasPermission('12-4-3-reset')"
              >重置</a-button
            >
            <a-button type="primary" @click="throttleSubmit" v-if="hasPermission('12-4-3-save')"
              >提交</a-button
            >
          </div>
        </div>
      </div>
    </div>
  </PageWrapper>
</template>

<script setup lang="ts">
  import { usePermission } from '/@/hooks/web/usePermission';
  import { PageWrapper } from '/@/components/Page';
  import { ref, onMounted } from 'vue';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useDebounceFn } from '@vueuse/core';
  import { getFormErrorMessage } from '/@/utils/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { setcustomfeaturecfg, getcustomfeaturecfg } from '/@/api/CustomFeatures/index';
  import { Tabs } from 'ant-design-vue';
  const { hasPermission } = usePermission();

  // 中间件配置表单内容
  const schemas: FormSchema[] = [
    {
      field: 'divider-basic',
      component: 'Divider',
      label: '中间件配置',
      colProps: {
        span: 24,
      },
      componentProps: {
        orientationMargin: '10px',
      },
    },
    {
      field: 'HostIP',
      component: 'Input',
      label: '地址：',
      colProps: {
        span: 14,
      },
      rules: [
        {
          required: true,
          message: '请输入地址',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'UserName',
      component: 'Input',
      label: '账号：',
      colProps: {
        span: 14,
      },
      rules: [
        {
          required: true,
          message: '请输入账号',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'Password',
      component: 'Input',
      label: '密码：',
      colProps: {
        span: 14,
      },
      rules: [
        {
          required: true,
          message: '请输入密码',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'Port',
      component: 'Input',
      label: '端口：',
      colProps: {
        span: 14,
      },
      rules: [
        {
          required: true,
          message: '请输入端口',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'VirtualHost',
      component: 'Input',
      label: '虚拟主机：',
      colProps: {
        span: 14,
      },
      rules: [
        {
          required: true,
          message: '请输入虚拟主机',
          trigger: ['change', 'blur'],
        },
      ],
    },
  ];
  // 设备表单内容

  let activeKey = ref(1);

  let loading = ref<boolean>(false);
  let oldValue = {};
  // 中间件配置表单
  const [registerForm, { validateFields, setFieldsValue }] = useForm({
    labelWidth: 120,
    schemas: schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  // 设备状态
  const [
    registerFormByStatus,
    { validateFields: validateFieldsByStatus, setFieldsValue: setFieldsValueByStatus },
  ] = useForm({
    labelWidth: 120,
    schemas: setSchemas('status'),
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  // 设备变量
  const [
    registerFormByVariable,
    { validateFields: validateFieldsByVariable, setFieldsValue: setFieldsValueByVariable },
  ] = useForm({
    labelWidth: 120,
    schemas: setSchemas('Variable'),
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  const { createMessage } = useMessage();
  const { t } = useI18n();

  onMounted(async () => {
    try {
      let res = await getcustomfeaturecfg();
      res.DeviceTagCfg = chanegeTypeString(res.DeviceTagCfg);
      res.DeviceStateCfg = chanegeTypeString(res.DeviceStateCfg);
      oldValue = res;
      setFieldsValueByVariable(res.DeviceTagCfg);
      setFieldsValueByStatus(res.DeviceStateCfg);
      setFieldsValue(res.MQConCfg);
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  });
  const throttleSubmit = useDebounceFn(handleSubmint, 500);
  function setSchemas(type) {
    let name = type === 'status' ? '设备状态' : '设备变量';
    const schemasByBase: FormSchema[] = [
      {
        field: 'QueuesName',
        component: 'Input',
        label: '队列名称：',
        colProps: {
          span: 14,
        },
        rules: [
          {
            required: true,
            message: `请输入${name}队列名称`,
            trigger: ['change', 'blur'],
          },
        ],
      },
      {
        field: 'PushIntervalMinutes',
        component: 'InputNumber',
        label: '推送周期：',
        colProps: {
          span: 14,
        },
        componentProps: {},
        rules: [
          {
            required: true,
            message: `请输入${name}推送周期`,
            trigger: ['change', 'blur'],
          },
        ],
        suffix: '(分钟)',
      },
      {
        field: 'Durable',
        component: 'RadioGroup',
        label: '队列持久：',
        colProps: {
          span: 14,
        },
        componentProps: {
          options: [
            {
              label: '是',
              value: '1',
            },
            {
              label: '否',
              value: '2',
            },
          ],
        },
        rules: [{ required: true, message: `请选择${name}队列持久`, trigger: ['change', 'blur'] }],
      },
      {
        field: 'Persistent',
        component: 'RadioGroup',
        label: '消息持久：',
        colProps: {
          span: 14,
        },
        componentProps: {
          options: [
            {
              label: '是',
              value: '1',
            },
            {
              label: '否',
              value: '2',
            },
          ],
        },
        rules: [{ required: true, message: `请选择${name}消息持久`, trigger: ['change', 'blur'] }],
      },
      {
        field: 'Enabled',
        component: 'RadioGroup',
        label: '是否启用：',
        colProps: {
          span: 14,
        },
        componentProps: {
          options: [
            {
              label: '是',
              value: '1',
            },
            {
              label: '否',
              value: '2',
            },
          ],
        },
        rules: [{ required: true, message: `请选择${name}是否启用`, trigger: ['change', 'blur'] }],
      },
    ];
    return schemasByBase;
  }
  function chanegeTypeString(val) {
    return {
      ...val,
      Enabled: val.Enabled ? '1' : '2',
      Persistent: val.Persistent ? '1' : '2',
      Durable: val.Durable ? '1' : '2',
    };
  }
  function chanegeTypeBoolean(val) {
    return {
      ...val,
      Enabled: val.Enabled === '1' ? true : false,
      Persistent: val.Persistent === '1' ? true : false,
      Durable: val.Durable === '1' ? true : false,
    };
  }
  async function handleSubmint() {
    loading.value = true;

    try {
      let res = await validateFields();
      let resByStatus = await validateFieldsByStatus();
      let resByVariabl = await validateFieldsByVariable();
      resByStatus = chanegeTypeBoolean(resByStatus);
      resByVariabl = chanegeTypeBoolean(resByVariabl);
      loading.value = false;
      let params: any = [];
      for (const resBykey in res) {
        params.push({ Key: `MQConCfg.${resBykey}`, Value: res[resBykey] });
      }
      for (const statusBykey in resByStatus) {
        params.push({ Key: `DeviceStateCfg.${statusBykey}`, Value: resByStatus[statusBykey] });
      }
      for (const variablBykey in resByVariabl) {
        params.push({ Key: `DeviceTagCfg.${variablBykey}`, Value: resByVariabl[variablBykey] });
      }
      await setcustomfeaturecfg([params]);
      loading.value = false;
      createMessage.success(t('layout.setting.operatingTitle'));
    } catch (error: any) {
      loading.value = false;

      console.log('not passing', error);
      getFormErrorMessage(error);
      let targetVal = error.errorFields.filter(
        (item) =>
          Array.isArray(item.errors) &&
          (item.errors[0].indexOf('设备状态') >= 0 || item.errors[0].indexOf('设备变量') >= 0),
      );
      if (targetVal.length > 0) {
        activeKey.value = targetVal[0].errors[0].indexOf('设备状态') >= 0 ? 1 : 2;
      }
    }
  }
  function handleResetFields() {
    setFieldsValueByVariable(oldValue.DeviceTagCfg);
    setFieldsValueByStatus(oldValue.DeviceStateCfg);
    setFieldsValue(oldValue.MQConCfg);
  }
</script>
<style lang="less" scoped>
  .p-4-tag {
    width: 100%;
    height: 100%;
    padding: 0px !important;
    .tag {
      position: relative;
      overflow: hidden;
      height: 100%;
      background-color: #fff;
      ::v-deep(.ant-col-14){
        margin: 10px 0;
      }
      .pagination-box {
        z-index: 9;
        padding: 10px 5px;
        box-sizing: border-box;
        position: absolute;
        width: 100%;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: #fff;
      }
    }
    .form-box {
      width: 100%;
      height: 100%;
      padding-bottom: 20px;
      box-sizing: border-box;
      // background-color: #fff;
    }
  }

  .btns {
    width: 100%;
    padding-left: 120px;
    box-sizing: border-box;

    .btns-one {
      margin-right: 10px;
    }
  }
</style>
